package org.example.booksystem.service;

import lombok.extern.slf4j.Slf4j;
import org.example.booksystem.mapper.BookInfoMapper;
import org.example.booksystem.moudel.BookInfo;
import org.example.booksystem.moudel.BookStatusEnum;
import org.example.booksystem.moudel.PageRequest;
import org.example.booksystem.moudel.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
@Slf4j
@Service
public class BookInfoService {


    @Autowired
    private BookInfoMapper mapper ;


    public List<BookInfo> getList() {
         List<BookInfo> list = mapper.getList() ;
         for(BookInfo bookInfo : list){
             int status = bookInfo.getStatus();
             if(status == 0){
                 bookInfo.setStatusCN("无效");
             }else if(status == 1){
                 bookInfo.setStatusCN("正常");
             }else if(status == 2){
                 bookInfo.setStatusCN("不允许借阅");
             }
         }
         return list ;
    }

    public String insertBook(BookInfo bookInfo) {
         if(!StringUtils.hasLength(bookInfo.getBookName()) ||
          !StringUtils.hasLength(bookInfo.getAuthor()) ||
         bookInfo.getCount()<0 || bookInfo.getPrice().compareTo(new BigDecimal(0))==-1 ||
          !StringUtils.hasLength(bookInfo.getPublish())){
             return "图书数据有误";
         }
         try{
             mapper.addBook(bookInfo);
         }catch(Exception e){
             e.printStackTrace();
             return "添加错误";
        }
         return "" ;
    }

    public PageResult<BookInfo> getBookListByPage(PageRequest pageRequest) {

         Integer count = mapper.count() ;
         List<BookInfo> bookInfoList = mapper.getBookListByPage(pageRequest) ;
         for(BookInfo bookInfo : bookInfoList){
             bookInfo.setStatusCN(BookStatusEnum.getNameByCode(bookInfo.getStatus()).getName());
         }
        return new PageResult<>(count , bookInfoList ,pageRequest);
    }

    public BookInfo getBookById(Integer bookId) {

       BookInfo bookInfo =  mapper.getBookById(bookId);

        return bookInfo ;
    }

    public boolean updateBook(BookInfo bookInfo) {
         log.info("修改图书:{}" , bookInfo);
         if(bookInfo.getId() < 1){
             return false ;
         }

        // 判断传过来的参数是否合法 ;
        try{
           Integer result =  mapper.updateBook(bookInfo) ;
           if(result <= 0){
               return false ;
           }
         return true ;
        }catch(Exception e){
              log.error("修改图书失败{}",e);
            return false ;
        }

    }

    public Integer batchDelete(List<Integer> ids) {
        if(ids == null) return 0;
        Integer result = mapper.batchDelete(ids);
        return result ;
    }
}
